package com.xplay.xpocker.room;

import com.xplay.xpocker.dvo.AbstractRoom;
import com.xplay.xpocker.dvo.RoomInfoInterface;
import com.xplay.xpocker.dvo.RoomRuleInterface;
import com.xplay.xpocker.room.mahjong.constant.MKey;
import com.xplay.xpocker.room.message.MessageContent;
import com.xplay.xpocker.room.message.MessageToClient;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public class RoomInfoTL {
    private RoomInfoTL() {

    }

    private static ThreadLocal<RoomThreadContent<?, ?, ?>> ROOM_CACHE = new ThreadLocal<>();

    public static void clear() {
        ROOM_CACHE.remove();
    }

    public static void set(RoomThreadContent<?, ?, ?> content) {
        ROOM_CACHE.set(content);
    }

    /**
     * 获取房间信息
     *
     * @return
     */

    public static <T extends RoomRuleInterface, R extends RoomInfoInterface, L> AbstractRoom<T, R, L> get() {
        return (AbstractRoom<T, R, L>) ROOM_CACHE.get().getRoomInfo();
    }

    /**
     * 将需要发送的消息添加到队列
     *
     * @param messageToClient
     */

    public static void addMessageToClient(Message messageToClient) {
        ROOM_CACHE.get().addMessage(messageToClient);
    }

    public static <T> void addMessageToClient(MessageContent<T> message, double delay) {
        if (message.getBody() instanceof MessageToClient) {
            ((MessageToClient) message.getBody()).put(MKey.sleep, delay);
        }
        ROOM_CACHE.get().addMessage(Message.MessageBuilder.init().setMessage(message)
                .setDelay(delay).builder());
    }

    public static <T> void addMessageToClient(MessageContent<T> message) {
        ROOM_CACHE.get().addMessage(Message.MessageBuilder.init().setMessage(message).builder());
    }

    public static <T> void addMessageToClient(List<MessageContent<T>> messageList, double delay) {
        if (messageList == null || messageList.size() == 0) {
            return;
        }
        for (MessageContent<?> content : messageList) {
            addMessageToClient(content, delay);
        }
    }

    public static <T> void addMessageToClient(List<MessageContent<T>> messageList) {
        if (messageList == null || messageList.size() == 0) {
            return;
        }
        for (MessageContent<?> content : messageList) {
            addMessageToClient(content);
        }
    }

    public static <T extends RoomRuleInterface, R extends RoomInfoInterface, L> void addLog(L log) {
        RoomThreadContent<T, R, L> content = (RoomThreadContent<T, R, L>) ROOM_CACHE.get();
        if (content != null && content.getRoomInfo() != null) {
            content.getRoomInfo().addLogs(log);
        }
    }

    public static List<Message> getMessageToClient() {
        LinkedList<Message> messageList = ROOM_CACHE.get().getMessageList();
        messageList.sort(Comparator.comparing(Message::getDelay));
        return messageList;
    }
}
